package com.zys.background.common.validator;



import com.zys.background.common.annotation.Phone;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author zys
 * @since 2022-11-11
 */
public class PhoneValidator implements ConstraintValidator<Phone, String> {
  private Pattern pattern;

  @Override
  public void initialize(Phone phoneAnnotation) {
    ConstraintValidator.super.initialize(phoneAnnotation);
    this.pattern = Pattern.compile(phoneAnnotation.regexp());
  }

  @Override
  public boolean isValid(String phone, ConstraintValidatorContext context) {
    return Objects.isNull(phone) || pattern.matcher(phone).matches();
  }
}
